import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/loading_dialog.dart';
import 'note_list_screen.dart';
import 'git_repo_screen.dart';
import 'todo_list_screen.dart';
import '../services/api_service.dart';
import 'date_query_screen.dart';
import 'calculator_screen.dart';
import 'sport_screen.dart';
import '../services/database_service.dart';

class HomeScreen extends StatelessWidget {
  static const bool showTodoFeature = false; // 控制是否显示待办事项
  const HomeScreen({super.key});

  Future<void> _checkAndGetToken(BuildContext context) async {
    final apiService = ApiService();
    final token = await apiService.getAccessToken();

    if (token == null) {
      // 显示token输入对话框
      final result = await showDialog<String>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          String inputToken = '';
          return AlertDialog(
            title: const Text('输入Gitee Token'),
            content: TextField(
              decoration: const InputDecoration(
                labelText: 'Access Token',
                hintText: '请输入您的Gitee Access Token',
              ),
              onChanged: (value) {
                inputToken = value;
              },
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () {
                  if (inputToken.isNotEmpty) {
                    Navigator.of(context).pop(inputToken);
                  }
                },
                child: const Text('确定'),
              ),
            ],
          );
        },
      );

      if (result != null) {
        // 保存token
        await apiService.saveAccessToken(result);
        // 跳转到Git仓库页面
        if (context.mounted) {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const GitRepoScreen()),
          );
        }
      }
    } else {
      // 已有token，直接跳转
      if (context.mounted) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => const GitRepoScreen()),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Forme'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.sync),
            tooltip: '同步数据库',
            onPressed: () async {
              final apiService = ApiService();
              final token = await apiService.getAccessToken();
              if (token == null) {
                if (!context.mounted) return;
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('请先配置Gitee Token'),
                  ),
                );
                return;
              }

              if (!context.mounted) return;
              LoadingDialog.show(context);
              String result = await DatabaseService().syncDatabase();

              if (context.mounted) {
                LoadingDialog.hide(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                      content: Text(result),
                      duration: const Duration(seconds: 2)),
                );
              }
            },
          ),
        ],
      ),
      body: SafeArea(
        child: GridView.count(
          padding: const EdgeInsets.all(16),
          crossAxisCount: 2,
          childAspectRatio: 0.9,
          // 宽高比，减小这个值可以增加高度
          mainAxisSpacing: 16,
          crossAxisSpacing: 16,
          children: [
            _buildFeatureCard(
              context,
              title: '便笺',
              description: '记录想法和笔记',
              icon: Icons.note_alt,
              color: Colors.blue,
              onTap: () async {
                final apiService = ApiService();
                final token = await apiService.getAccessToken();
                if (token == null) {
                  // 弹出toast
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('请先点击Git仓库配置token'),
                      duration: Duration(seconds: 2), // 显示时长
                      behavior: SnackBarBehavior.floating, // 悬浮样式
                      margin: EdgeInsets.only(
                          bottom: 50, left: 20, right: 20), // 位置调整
                    ),
                  );
                  return;
                }
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => const NoteListScreen()),
                );
              },
            ),
            // _buildFeatureCard(
            //     context,
            //     title: '待办事项',
            //     description: '管理任务和计划',
            //     icon: Icons.task_alt,
            //     color: Colors.purple,
            //     onTap: () async {
            //       final apiService = ApiService();
            //       final token = await apiService.getAccessToken();
            //       if (token == null) {
            //         // 弹出toast
            //         ScaffoldMessenger.of(context).showSnackBar(
            //           const SnackBar(
            //             content: Text('请先点击Git仓库配置token'),
            //             duration: Duration(seconds: 2), // 显示时长
            //             behavior: SnackBarBehavior.floating, // 悬浮样式
            //             margin: EdgeInsets.only(
            //                 bottom: 50, left: 20, right: 20), // 位置调整
            //           ),
            //         );
            //         return;
            //       }
            //       Navigator.push(
            //         context,
            //         MaterialPageRoute(
            //             builder: (context) => const TodoListScreen()),
            //       );
            //     },
            //   ),
            _buildFeatureCard(
              context,
              title: 'Git仓库',
              description: '管理gitee仓库',
              icon: Icons.folder,
              color: Colors.green,
              onTap: () => _checkAndGetToken(context),
            ),
            _buildFeatureCard(
              context,
              title: '日期查询',
              description: '查星座和农历',
              icon: Icons.calendar_today,
              color: Colors.orange,
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => const DateQueryScreen()),
                );
              },
            ),
            _buildFeatureCard(
              context,
              title: '计算器',
              description: '计算日常所需',
              icon: Icons.calculate,
              color: Colors.indigo,
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => const CalculatorScreen()),
                );
              },
            ),
            _buildFeatureCard(
              context,
              title: '运动',
              description: '记录锻炼与健康',
              icon: Icons.fitness_center,
              color: Colors.teal,
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const SportScreen()),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFeatureCard(
    BuildContext context, {
    required String title,
    required String description,
    required IconData icon,
    required Color color,
    required VoidCallback onTap,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16),
        child: Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  icon,
                  size: 32,
                  color: color,
                ),
              ),
              const SizedBox(height: 16),
              Text(
                title,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                description,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
                maxLines: 1, // 限制最大行数
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ],
          ),
        ),
      ),
    );
  }
}
